using MediatR;
using UniversalAdmin.Domain.DomainEvents;

namespace UniversalAdmin.Domain.Entities.App
{
  public class AppUser : EntityBase
  {
    public string Username { get; set; } = null!; // 用户名 (3-50字符)
    public string Password { get; set; } = null!; // 加密后的密码
    public string Email { get; set; } = null!; // 邮箱地址 (唯一)
    public string? Phone { get; set; } // 手机号 (可空)
    public string? Avatar { get; set; } // 头像URL (可空)
    public int AccountStatus { get; set; }  // 账户状态: 0=正常,1=临时锁定,2=管理员禁用
    public int FailedLoginAttempts { get; set; }  // 连续登录失败次数
    public DateTime? LockedUntil { get; set; } // 锁定截止时间 (可空)
    public DateTime? LastFailedLogin { get; set; } // 最后失败登录时间 (可空)
    public DateTime? LastLoginTime { get; set; } // 最后登录时间 (可空)
    public DateTime? LastActivityTime { get; set; } // 最后活动时间 (可空)

    public string Salt { get; set; } = null!; // 盐值

    public ICollection<AppRole> Roles { get; set; } = new List<AppRole>();

    public void AssignRole(AppRole role)
    {
        if (!Roles.Any(r => r.Id == role.Id))
        {
            Roles.Add(role);
        }
    }

    public void RemoveRole(AppRole role)
    {
        var existingRole = Roles.FirstOrDefault(r => r.Id == role.Id);
        if (existingRole != null)
        {
            Roles.Remove(existingRole);
        }
    }

    // public bool HasPermission(string permissionCode)
    // {
    //     return Roles.Any(r => r.HasPermission(permissionCode));
    // }

    public void ChangePassword(string oldHash, string newHash){
      if(oldHash == newHash) throw new Exception("新密码不能与旧密码相同");
      Password = newHash;
    }

    // 领域事件发布
    public void OnCreated() => AddDomainEvent(new UserCreatedEvent(this));
    public void OnUpdated() => AddDomainEvent(new UserUpdatedEvent(this));
    public void OnDeleted() => AddDomainEvent(new UserDeletedEvent(this));
  }


}

